package cast.it.zhang.sqlitedemo;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import cast.it.zhang.sqlitedemo.database.DatabaseHelper;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private Button button_data;
    private DatabaseHelper helper;
    private Button bt_add;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        helper = new DatabaseHelper(this);
        helper.getWritableDatabase();
        /**
         * 创建数据库
         */
        button_data = (Button) findViewById(R.id.bt_create_database);
        button_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                helper.getWritableDatabase();
            }
        });

        /**
         * 添加数据
         */
        bt_add = (Button) findViewById(R.id.add_data);
        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = helper.getWritableDatabase();
                ContentValues values = new ContentValues();
                //添加第一组数据
                values.put("name","zhangsan");
                values.put("auther","Ban brown1");
                values.put("pages",145);
                values.put("price",13.45);
                db.insert("Book",null,values);//插入第一天数据
                values.clear();

                //添加第二组数据
                values.put("name","lisi");
                values.put("auther","Ban brown2");
                values.put("pages",111);
                values.put("price",3.89);
                db.insert("Book",null,values);//插入第二条数据
                db.close();
            }
        });

        /**
         * 更改数据
         */
        Button bt_update = (Button) findViewById(R.id.update_data);
        bt_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData1();
            }
        });

        /**
         * 删除数据
         */
        Button bt_delete = (Button) findViewById(R.id.delete_data);
        bt_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = helper.getWritableDatabase();
                db.delete("Book","pages > ?",new String[] {"140"});
                db.close();
            }
        });

        /**
         * 获取数据
         *
         */
        Button bt_query = (Button) findViewById(R.id.query_data);
        bt_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = helper.getReadableDatabase();
                //查询Book表中所有的数据
                Cursor cursor = db.query("Book",null,null,null,null,null,null);

                /**
                 * 这里先进行判断是否是在第一行，如果是，直接获取数据，然后再判断是否有
                 * 下一行，进行while循环的判断，去遍历查询每一行数据，cursor.getColumnIndex
                 * 方法会获取到某一列在表中对应的位置索引。
                 */
                if(cursor.moveToFirst()) {
                    do {
                        String name = cursor.getString(cursor.getColumnIndex("name"));
                        String auther = cursor.getString(cursor.getColumnIndex("auther"));
                        int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                        double price = cursor.getInt(cursor.getColumnIndex("price"));

                        Log.d(TAG,"name = "+name);
                        Log.d(TAG,"auther = "+auther);
                        Log.d(TAG,"pages = "+pages);
                        Log.d(TAG,"price = "+price);
                    } while (cursor.moveToNext());
                }
                cursor.close();
                db.close();
            }
        });

        /**
         * 开启事务，进行数据的替换操作
         */
        Button bt_replace = (Button) findViewById(R.id.replace_data);
        bt_replace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*SQLiteDatabase db = helper.getWritableDatabase();
                db.beginTransaction();//开启事务

                try {
                    db.delete("Book",null,null);

                    *//**
                     * 如果在这里抛出一个异常，出现问题，有了事务，执行失败，数据就不会被替换
                     * 如果去掉，事务执行成功就会被替换。
                     *//*
                    if(true) {
                        //在这里手动抛出一个异常，让事务失败
//                        throw new NullPointerException();
                    }
                    ContentValues values = new ContentValues();
                    values.put("name","wangwu");
                    values.put("auther","Ban brown3");
                    values.put("pages",140);
                    values.put("price",13);
                    db.insert("Book",null,values);
                    db.setTransactionSuccessful();//执行事务成功
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    db.endTransaction();//事务结束
                }*/


                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        updateData1();
                    }
                }).start();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        updateData2();
                    }
                }).start();
            }
        });
    }

    private void updateData1() {
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("price",888);
        db.update("Book",values,"name=?",new String[] {"lisi"});
        db.close();
    }

    private void updateData2() {
        DatabaseHelper helper1 = new DatabaseHelper(this);
        SQLiteDatabase db = helper1.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("price",666);
        db.update("Book",values,"name=?",new String[] {"lisi"});
        db.close();
    }
}
